from flask import Flask, request, send_from_directory, render_template
from werkzeug.utils import secure_filename
import os
import uuid
from flask_cors import CORS
from VideoZip.com.xu.ZipPictureOrVideo import ZipPictureOrVideo

import json

app = Flask( __name__ )

UPLOAD_FOLDER = '/Users/xuyihang/file/'
CORS( app )

'''
  视频文件上传方法
'''


@app.route( "/" )
def voideIndex():
    return render_template( 'index.html' )


@app.route( "/voideoFilePush", methods=['GET', 'POST'] )
def voideoFile():
    fileName = {}
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    if request.method == 'POST':
        f = request.files['file']
        f.save( os.path.join( app.config['UPLOAD_FOLDER'], secure_filename( f.filename ) ) )
        filePath = UPLOAD_FOLDER
        fileOutName = f.filename + '_out.mp4';
        fileName["fileOutName"] = fileOutName
        file = ZipPictureOrVideo( filePath, f.filename, fileOutName )
        if file.is_picture:
            print( file.start_compress_pic() )
        elif file.is_video:
            print( file.start_compress_video() )
        else:
            print( '该文件不是图片或者视频' )
        dumps = json.dumps( fileName )

    return dumps


@app.route( "/getZipVoide" )
def getZipVoide():
    if request.method == 'GET':
        _fileName = request.args.get( 'fileName' )
        dirpath = os.path.join( UPLOAD_FOLDER )  # 这里是下在目录，从工程的根目录写起，比如你要下载static/js里面的js文件，这里就要写“static/js”
        return send_from_directory( dirpath, _fileName, as_attachment=True )


if __name__ == '__main__':
    app.run( '0.0.0.0', '8081' )
